import React, { useCallback, useEffect, useState } from "react";
import { Form, Button, Popconfirm, Space, DatePicker, Dropdown, Menu, Image, message, InputNumber } from "antd";
import useColumns from "./cloumns";
import CombRemarkModal from "./component/CombRemarkModal";
import CombAnalyticFormula from "./component/CombAnalyticFormula";
import AutomaticGenerateSetModal from "./component/AutomaticGenerateSetModal";
import LogCombGoods from "./component/LogCombGoods";
import InventorySynchronizationModal from "./component/InventorySynchronizationModal";
import ImportCombGoods from "./component/ImportCombGoods";
import ActionExportExcelModal from "./component/ActionExportExcelModal"; // 导出弹窗
import StockSyncModal from "./component/StockSyncModal";
import {
	getCombinationSkuList,
	updateSyncStatus,
	updateSkuStatus,
	combinationDelSubmit,
	combinationBatchDelSubmit,
	getCombinationInfo,
	getGoodsSkuPage,
    queryWaitCreateCombination
} from "./service";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import SelectActions from "@/views/components/SelectActions";
import { useNavigate, useLocation } from "react-router-dom";
import { FileTextOutlined } from "@ant-design/icons";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import ColsSetting from "@/views/components/SearchTable/ColsSetting";
import { useColsSetting } from "@/views/components/SearchTable/ColsSetting/hook";
import IconFont from "@/components/IconFont";
import GenerateCombination from './component/GenerateCombination/index';
import EncodeSetting from '../common/EncodeSetting';

const soldPurchasePage = () => {
	const [visible, setVisible] = useState(0);
	const [records, setRecords] = useState({});
	const [update, setUpdate] = useState(null);
	const [exelVisible, setExelVisible] = useState("EditModal");
	const [type, setType] = useState([]);
	const [typeComb, setCombType] = useState("");
	const [logType, setLogType] = useState("");
	const [analytic, setAnalytic] = useState("");
	const [syncStatus, setSyncStatus] = useState(1);
	const [infoData, setInfoData] = useState({});
	const navigate = useNavigate();
	const location = useLocation();
	const [open, setOpen] = useState(false);
    const [waitCombineNum, setWaitCombineNum] = useState(0);

	// 接口
	const tableRequest = getCombinationSkuList;

    useEffect(() => {
        getWaitCreateCombination();
    }, [])

    //获取待生成组合数量
    const getWaitCreateCombination = async () => {
        const { success, data } = await queryWaitCreateCombination();
        if(success) {
            setWaitCombineNum(data);
        }
    }


	const getGoodsSkuPageList = (status, r, type, recordData) => {
		navigate("/views/goods/combination/add", {
			state: { record: r, type: type, data: recordData, status: new Date().getTime() }
		});
	};
	const getCombinationInfoList = async (status, r, type) => {
		const { data, success } = await getCombinationInfo({
			id: r.id
		});
		const recordData = data;
		if (success) {
			if (type == "update") {
				getGoodsSkuPageList(status, r, type, recordData);
			} else {
				navigate("/views/goods/combination/add", {
					state: { record: r, type: type, data: data, status: new Date().getTime() }
				});
			}
		}
		setInfoData(data);
	};
	const addGoodsClick = (status, r, type) => {
		if (status === 1) {
			if (type == "update" || type == "copy") {
				return getCombinationInfoList(status, r, type);
			} else {
				return navigate("/views/goods/combination/add", { state: { type: type } });
			}
		} else {
			return navigate("/views/goods/combination/addComb", { state: { type: new Date().getTime() } });
		}
	};
	useEffect(() => {
		setColumns(defaultColumns);
	}, [location.state]);
	// 删除
	const confirm = async item => {
		const { success } = await combinationDelSubmit({
			id: item.id
		});
		if (success) {
			fetchList();
			message.success("删除操作成功");
		}
	};
	const cancel = () => {};
	const { defaultColumns } = useColumns({
		addGoodsClick,
		confirm,
		cancel
	});
	// 批量删除
	const batchDelConfirm = async () => {
		const { success } = await combinationBatchDelSubmit({
			ids: selectedKeys
		});
		if (success) {
			fetchList();
			message.success("批量删除操作成功");
		}
	};
	const [columns, setColumns] = useState(defaultColumns);
	const commonHandleClick = (status, r, type) => {
		setCombType(type);
		setRecords(r);
		if (status == 4 || status == 5) {
			if (selectedRows.length) {
				setVisible(status);
			} else {
				message.warning("需要选择商品");
			}
		} else {
			setInfoData({});
			setVisible(status);
		}
	};
	useEffect(() => {
		if (location.state?.type === "request") {
			fetchList();
		}
	}, [location.state]);
	const tableKey = "index1231231";

	const { filterColumns, realColumns, saveRemoteData, initColsSetting } = useColsSetting({ tableKey, columns });

	const { selectedKeys, selectedRows, dataSource, form, fetchList, pagination, query, searchSimpleTableProps } = useTableConfig({
		tableKey,
		rowKey: "id",
		columns,
		tableRequest,
		autoFetch: true,
		hasPagination: true,
		hasQuickSearch: true,
		beforeQuerySearch: ({ API_DATA }) => {
			API_DATA.type = 1;
			return {
				...API_DATA
				// type: 1
			};
		},
		resetSourceData: false,
		pageSize: 50,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true
	});
	const ColsSettingProps = {
		tableKey,
		defaultColumns: filterColumns,
		columns: realColumns,
		initColsSetting,
		saveRemoteData
	};
	const combinationExportExceClickl = async type => {
        if(type == '3') {
            if(selectedKeys.length == 0) {
                return message.info('请选择组合商品')
            }
        }
		setExelVisible("ProgressModal");
		setType(type);
	};
	const spuParam = form.getFieldsValue();

	const realProps = {
		createTaskData: {
			businessParam: JSON.stringify({
				skuIds: type == 3 ? selectedKeys : [],
				skuParam: type == 2 ? spuParam : {},
				businessKey: type
			}),
			taskType: 3003
		},
		onCancel() {
			setExelVisible("");
		}
	};
	const CheckCombGoodsProps = {
		visible,
		query,
		fetchList,
		update,
		syncStatus,
		typeComb,
		infoData,
		checkedIds: selectedKeys,
		checkedRows: selectedRows,
		records,
		dataSource,
		handleOk() {},
		onCancel() {
			setVisible(0);
		}
	};
	useEffect(() => {}, [logType]);
	const CombGoodsLogProps = {
		visible,
		query,
		fetchList,
		records,
		logType,
		analytic,
		title:
			logType == "updateLog"
				? "修改日志"
				: logType == "deleteLog"
					? "删除日志"
					: analytic == "formula"
						? "组合装解析公式"
						: "自动生成设置",
		handleOk() {},
		onCancel() {
			setLogType("");
			setAnalytic("");
		}
	};

	const onSnycChange = e => {
		setSyncStatus(e);
		setVisible("StockSync");
	};
	const onChange = async (e, val) => {
		if (selectedRows.length) {
			if (val == 1) {
				const { success } = await updateSkuStatus({
					ids: selectedKeys,
					status: e
				});
				if (success) {
					message.success("操作成功");
				}
			} else if (val == 2) {
				const { success } = await updateSyncStatus({
					ids: selectedKeys,
					status: e
				});
				if (success) {
					message.success("操作成功");
				}
			}
		} else {
			message.warning("请选择商品");
		}
	};

	const leftBtns = (
		<Space>
			<Dropdown
				trigger="click"
				overlay={
					<Menu>
						<Menu.Item key="1" onClick={() => addGoodsClick(1, "", "add")}>
							单个组合商品
						</Menu.Item>
						<Menu.Item key="2" onClick={() => addGoodsClick(2)}>
							批量组合商品
						</Menu.Item>
					</Menu>
				}
			>
				<Button type="primary">
					创建组合
					<DownOutlined />
				</Button>
			</Dropdown>

            <Button onClick={() => {setVisible('generateCombination')}}>
				<span className="common-color9">待生成组合{`(${waitCombineNum})`}</span>
			</Button>


			<Button>
				<Popconfirm title="确定批量删除数据?" onConfirm={() => batchDelConfirm()} onCancel={cancel}>
					<a href="#">批量删除</a>
				</Popconfirm>
			</Button>

			{/* <SelectActions
				onClick={e => {
					onChange(e, 1);
				}}
				name="启用/禁用"
				width="80px"
				options={[
					{
						label: "禁用",
						value: 1
					},
					{
						label: "启用",
						value: 2
					}
				]}
			/> */}
			<SelectActions
				name="开启/禁止库存同步"
				width="130px"
				onClick={e => {
					onSnycChange(e);
				}}
				options={[
					{
						label: "开启同步",
						value: 1
					},
					{
						label: "禁止同步",
						value: 2
					}
				]}
			/>

			<Button onClick={() => commonHandleClick(5)}>手工同步库存</Button>

			<Button onClick={() => commonHandleClick(4)}>组合备注</Button>
			<Button onClick={() => commonHandleClick(3)}>导入</Button>

			<SelectActions
				name="导出"
				options={[
					{
						key: "1",
						label: "导出所有的商品资料"
					},
					{
						key: "2",
						label: "导出筛选后的商品资料"
					},
					{
						key: "3",
						label: "导出已勾选的商品资料"
					}
				]}
				onClick={key => {
					combinationExportExceClickl(key);
				}}
			></SelectActions>
		</Space>
	);

	const rightBtns = (
		<>
			<SelectActions
				options={[
					{
						value: "商品修改日志",
						label: "商品修改日志",
						onClick: () => {
							setLogType("updateLog");
						}
					},
					{
						value: "商品删除日志",
						label: "商品删除日志",
						onClick: () => {
							setLogType("deleteLog");
						}
					}
				]}
			>
				<FileTextOutlined className="main-color" />
				<span className="line-height-21" style={{ display: "inline-block" }}>
					查看日志
				</span>
			</SelectActions>
			<Button
				type="text"
				onClick={() => {
					setAnalytic("set");
				}}
			>
				<IconFont type="iconzidongshengchengshezhi" />
				自动生成设置
			</Button>
			<Button
				type="text"
				onClick={() => {
					setAnalytic("formula");
				}}
			>
				<IconFont type="iconjiexigongshi" />
				组合装解析公式
			</Button>
			{/* <SelectActions
				options={[
					{
						value: "列表配置",
						label: "列表配置",
						onClick: () => {
							setOpen(true);
						}
					},
					{
						value: "自动生成设置",
						label: "自动生成设置",
						onClick: () => {
							setAnalytic("set");
						}
					},
					{
						value: "组合装解析公式",
						label: "组合装解析公式",
						onClick: () => {
							setAnalytic("formula");
						}
					}
				]}
			>
				<IconFont type="icona-lujing12" />
				<span className="line-height-21" style={{ display: "inline-block" }}>
					列表配置
				</span>
			</SelectActions> */}
			{/* <SelectActions
				options={[
					{
						value: "自动生成设置",
						label: "自动生成设置",
						onClick: () => {
							setAnalytic("set");
						}
					},
					{
						value: "组合装解析公式",
						label: "组合装解析公式",
						onClick: () => {
							setAnalytic("formula");
						}
					}
				]}
			>
				<FileTextOutlined className="main-color" />
				<span className="line-height-21" style={{ display: "inline-block" }}>
					组合装解析公式
				</span>
			</SelectActions> */}
		</>
	);

    const GenerateCombinationProps = {
        visible: visible == 'generateCombination',
        handleCancel() {
            setVisible(false);
            getWaitCreateCombination();
        }
    }

	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={leftBtns} rightBtns={rightBtns} mounted={false} {...searchSimpleTableProps} />
			{visible == 3 && <ImportCombGoods {...CheckCombGoodsProps} />}
			{visible == 4 && <CombRemarkModal {...CheckCombGoodsProps} />}
			{visible == 5 && <InventorySynchronizationModal {...CheckCombGoodsProps} />}
			{visible == "StockSync" && <StockSyncModal {...CheckCombGoodsProps} />}
			{visible == "generateCombination" && <GenerateCombination {...GenerateCombinationProps} />}

			{/* {visible == 6 && <SelectLog {...CheckSelectLogProps} />} */}
			{exelVisible == "ProgressModal" && <ActionExportExcelModal {...realProps} />}
			{(logType == "updateLog" || logType == "deleteLog") && <LogCombGoods {...CombGoodsLogProps} />}
			{analytic == "formula" && <CombAnalyticFormula {...CombGoodsLogProps} />}

			{analytic == "set" && <EncodeSetting {...CombGoodsLogProps} />}
			<ColsSetting {...ColsSettingProps} open={open} setOpen={setOpen} />
		</>
	);
};

export default React.memo(soldPurchasePage, () => {
	return true;
});
